package org.example.onlinejudge.controller;

import org.example.onlinejudge.model.User;
import org.example.onlinejudge.service.UserService;
import org.example.onlinejudge.repository.RoleRepository;
import org.example.onlinejudge.repository.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 管理员用户管理控制器
 */
@Controller
@RequestMapping("/admin/users")
@PreAuthorize("hasRole('0')") // 仅管理员可访问
public class AdminUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    /**
     * 用户列表页面
     */
    @GetMapping
    @PreAuthorize("hasAuthority('user:view')")
    public String userList(Model model) {
        System.out.println("\n========== 访问用户管理页面 ==========");
        
        var users = userService.findAllUsers();
        var roles = roleRepository.findAll();
        
        System.out.println("✓ 查询到用户数量: " + users.size());
        System.out.println("✓ 查询到角色数量: " + roles.size());
        
        if (!users.isEmpty()) {
            System.out.println("✓ 第一个用户: " + users.get(0).getUsername());
        }
        
        model.addAttribute("users", users);
        model.addAttribute("roles", roles);
        model.addAttribute("allPermissions", permissionRepository.findAll());
        
        System.out.println("✓ 返回模板: admin/users");
        System.out.println("========== 处理完成 ==========\n");
        
        return "admin/users";
    }

    /**
     * 处理添加用户请求
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('user:add')")
    public String addUser(@RequestParam("username") String username,
                         @RequestParam("password") String password,
                         @RequestParam(value = "email", required = false) String email,
                         @RequestParam(value = "name", required = false) String name,
                         @RequestParam("roleCode") String roleCode,
                         RedirectAttributes redirectAttributes) {
        try {
            userService.createUserWithRole(username, password, email, name, roleCode);
            redirectAttributes.addFlashAttribute("success", "用户添加成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }

    /**
     * 处理编辑用户请求
     */
    @PostMapping("/edit/{id}")
    @PreAuthorize("hasAuthority('user:edit')")
    public String editUser(@PathVariable Long id,
                          @RequestParam(value = "email", required = false) String email,
                          @RequestParam(value = "name", required = false) String name,
                          @RequestParam(value = "enabled", defaultValue = "false") Boolean enabled,
                          RedirectAttributes redirectAttributes) {
        try {
            User user = userService.findById(id)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            user.setEmail(email);
            user.setName(name);
            user.setEnabled(enabled);
            
            userService.updateUser(user);
            redirectAttributes.addFlashAttribute("success", "用户信息更新成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }

    /**
     * 修改用户角色
     */
    @PostMapping("/change-role/{id}")
    @PreAuthorize("hasAuthority('user:edit')")
    public String changeUserRole(@PathVariable Long id,
                                @RequestParam("roleId") Long roleId,
                                RedirectAttributes redirectAttributes) {
        try {
            // 先移除所有角色
            User user = userService.findById(id).orElseThrow();
            user.getRoles().clear();
            userService.updateUser(user);
            
            // 添加新角色
            userService.addRoleToUser(id, roleId);
            
            redirectAttributes.addFlashAttribute("success", "角色修改成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "角色修改失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }

    /**
     * 重置密码
     */
    @PostMapping("/reset-password/{id}")
    @PreAuthorize("hasAuthority('user:edit')")
    public String resetPassword(@PathVariable Long id,
                               @RequestParam("newPassword") String newPassword,
                               RedirectAttributes redirectAttributes) {
        try {
            userService.changePassword(id, newPassword);
            redirectAttributes.addFlashAttribute("success", "密码重置成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "密码重置失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('user:delete')")
    public String deleteUser(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            User user = userService.findById(id).orElseThrow();
            
            // 防止删除管理员账号
            if ("admin".equals(user.getUsername()) || 
                "superadmin".equals(user.getUsername()) || 
                "manager".equals(user.getUsername())) {
                redirectAttributes.addFlashAttribute("error", "不能删除系统管理员账号");
                return "redirect:/admin/users";
            }
            
            userService.deleteUser(id);
            redirectAttributes.addFlashAttribute("success", "用户删除成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }

    /**
     * 启用/禁用用户
     */
    @PostMapping("/toggle-status/{id}")
    @PreAuthorize("hasAuthority('user:edit')")
    public String toggleUserStatus(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            User user = userService.findById(id).orElseThrow();
            userService.setUserEnabled(id, !user.getEnabled());
            
            String status = !user.getEnabled() ? "启用" : "禁用";
            redirectAttributes.addFlashAttribute("success", "用户已" + status);
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "操作失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }

    /**
     * 为用户添加权限
     */
    @PostMapping("/add-permission/{userId}")
    @PreAuthorize("hasAuthority('user:edit')")
    public String addPermissionToUser(@PathVariable Long userId,
                                     @RequestParam("permissionId") Long permissionId,
                                     RedirectAttributes redirectAttributes) {
        try {
            userService.addPermissionToUser(userId, permissionId);
            redirectAttributes.addFlashAttribute("success", "权限添加成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "权限添加失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }

    /**
     * 移除用户权限
     */
    @PostMapping("/remove-permission/{userId}")
    @PreAuthorize("hasAuthority('user:edit')")
    public String removePermissionFromUser(@PathVariable Long userId,
                                          @RequestParam("permissionId") Long permissionId,
                                          RedirectAttributes redirectAttributes) {
        try {
            userService.removePermissionFromUser(userId, permissionId);
            redirectAttributes.addFlashAttribute("success", "权限移除成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "权限移除失败：" + e.getMessage());
            return "redirect:/admin/users";
        }
    }
}


